// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// o [author] rhyme_lph
// B [email]  rhymelph@gmail.com
// a [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/employee_contact_entity.dart';
import 'package:finance_app/src/entities/salary_user_working_days_entity.dart';
import 'package:finance_app/src/provider/hr_payroll/payroll/set_salary_period_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common/tag_widget.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/list_item/time_select_item.dart';
import 'package:finance_app/src/widgets/pop/normal_border_pop.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

@RouterMeta(paramName: "setSalaryPeriodPage")
class SetSalaryPeriodPage extends StatefulWidget {
  final List<EmployeeContactEntity> data;

  const SetSalaryPeriodPage({Key key, this.data}) : super(key: key);

  @override
  _SetSalaryPeriodPageState createState() => _SetSalaryPeriodPageState();
}

class _SetSalaryPeriodPageState extends State<SetSalaryPeriodPage>
    with PagePresenter<SetSalaryPeriodPage, SetSalaryPeriodProvider> {
  @override
  PreferredSizeWidget get appBar =>
      getDefaultAppBar(title: S.current.set_salary_period, actions: [
        NormalDoneTextButton(
          onTap: provider.onDone,
        ),
      ]);

  @override
  void initState() {
    provider.initData(widget.data);

    super.initState();
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            listBuilder<String>(
              selector: (_, __) => __.currentSelectDatePop,
              builder: (BuildContext context, String value, Widget child) =>
                  NormalBorderPop<String>(
                select: value,
                buildDisplayName: (e) => e,
                group: provider.datePopList,
                onSelect: provider.onChangeDate,
              ),
            ),
            AppSpaces.h15,
            _buildFormToDateWidget(),
            AppSpaces.h20,
            ListHeaderItem(
              title: S.current.total_working_days,
              fontWeight: FontWeight.w700,
            ),
            PressedOpacityButton(
              onPressed: () {
                provider.onNavLeaveDetails();
              },
              child: Container(
                alignment: Alignment.centerRight,
                margin:
                    EdgeInsets.symmetric(vertical: 15, horizontal: getDp(35)),
                child: Text(
                  S.current.see_leave_details,
                  style: TextStyle(
                    color: aceBlueColor,
                    fontSize: getSp(16),
                    fontWeight: FontWeight.w700,
                    height: 14 / 16,
                  ),
                ),
              ),
            ),
            Divider(height: getDp(0), color: aceGrayColor, thickness: 0.5),
            Expanded(
              child: ListView.builder(
                  itemCount: provider.data.length,
                  itemBuilder: (context, i) => _buildItem(provider.data, i)),
            ),
          ],
        ),
      );

  Widget _buildItem(List<SalaryUserWorkingDaysEntity> data, int i) {
    return listBuilder<SalaryUserWorkingDaysEntity>(
      selector: (_, __) => __.data[i],
      builder: (BuildContext context, SalaryUserWorkingDaysEntity value,
              Widget child) =>
          Container(
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(color: aceGrayColor, width: getDp(0.5)),
          ),
        ),
        padding: EdgeInsets.symmetric(
          horizontal: getDp(35),
          vertical: getDp(10),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Text(
                  value.name,
                  style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 16,
                  ),
                ),
                if (value.beforeHiringDate)
                  Padding(
                    padding: const EdgeInsets.only(left: 8.0),
                    child: RedTagWidget(
                      content: S.current.before_hiring_date,
                    ),
                  ),
              ],
            ),

            _buildNumberInput(data[i]),
            // Text(value.days.toString())
          ],
        ),
      ),
    );
  }

  Widget _buildNumberInput(SalaryUserWorkingDaysEntity data) {
    final TextEditingController controller =
        TextEditingController(text: data.days.toStringAsFixed(1));
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        PressedOpacityButton(
          onPressed: () {
            if (data.days <= 0) return;
            FocusManager.instance.primaryFocus.unfocus();
            setState(() {
              data.days--;
            });
          },
          child: SvgPicture.asset(
            A.assetsImagesStyleMinus,
            width: getDp(24),
            height: getDp(24),
            color: data.days > 0 ? null : aceGrayColor,
          ),
        ),
        SizedBox(
          width: getDp(65),
          child: TextField(
            inputFormatters: [
              leaveDaysInputFormatter,
            ],
            // enabled: FormEditStatusInheritedWidget.ofEnable(context),
            scrollPadding: EdgeInsets.zero,
            decoration: InputDecoration(
              border: InputBorder.none,
              enabledBorder: InputBorder.none,
            ),
            controller: controller,
            onChanged: (String text) {
              if (text == null || text == "") {
                setState(() {
                  data.days = 0;
                });
                return;
              }
              data.days = num.tryParse(text);
            },
            style: TextStyle(
              color: aceBlueColor,
              fontSize: getSp(16),
              fontWeight: FontWeight.w700,
            ),
            textAlign: TextAlign.center,
          ),
        ),
        PressedOpacityButton(
          onPressed: () {
            FocusManager.instance.primaryFocus.unfocus();
            setState(() {
              data.days++;
            });
          },
          child: SvgPicture.asset(
            A.assetsImagesStylePlus,
            width: getDp(24),
            height: getDp(24),
            // color: FormEditStatusInheritedWidget.ofEnable(context)
            //     ? null
            //     : aceGrayColor,
          ),
        ),
      ],
    );
  }

  Widget _buildFormToDateWidget() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: getDp(35)),
      child: Row(
        children: [
          Expanded(
            child: listBuilder<DateTime>(
              selector: (_, __) => __.from,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  TimeSelectItem(
                      title: S.current.from,
                      value: value == null
                          ? Config.settingInfo.dateFormat.toUpperCase() ??
                              "DD MMM YYYY"
                          : DateTimeUtils.formatGlobalDateTime(value),
                      onTap: provider.onSelectFrom),
            ),
          ),
          SizedBox(
            width: getDp(13),
          ),
          Expanded(
            child: listBuilder<DateTime>(
              selector: (_, __) => __.to,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  TimeSelectItem(
                      title: S.current.to,
                      value: value == null
                          ? Config.settingInfo.dateFormat.toUpperCase() ??
                              "DD MMM YYYY"
                          : DateTimeUtils.formatGlobalDateTime(value),
                      onTap: provider.onSelectTo),
            ),
          ),
        ],
      ),
    );
  }
}
